/**
 * Copyright (c) 2009 blurredVision
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
 * associated documentation files (the "Software"), to deal in the Software without restriction, 
 * including without limitation the rights to use, copy, modify, merge, publish, distribute, 
 * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is 
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or 
 * substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT 
 * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT 
 * OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
#include "StdAfx.h"
#include "StreamingSound_OpenAL.h"
#include "StreamingBuffer_OpenAL.h"
#include <vector>
#include <vorbis/vorbisfile.h>
#include "vorbis/codec.h"
#include "audio_openal.h"

namespace openAL{

StreamingSound_OpenAL::StreamingSound_OpenAL(StreamingBuffer_OpenAL* pStreamingBuffer):
	AbstractSound_OpenAL()
{
	m_iPriority = 1;
	
	m_pStreamingBuffer = pStreamingBuffer;

	// Generate some AL Buffers for streaming
	alGenBuffers(NUMBUFFERS, m_aBuffers);

	m_bBufferHasMoreSamples = true;

	m_fFadeFactor = 1;
	m_fDeltaFade = 0;
}

StreamingSound_OpenAL::~StreamingSound_OpenAL(void)
{
	if (m_sourceID == 0) {
		ALint	iState;		
		alGetSourcei(m_sourceID, AL_SOURCE_STATE, &iState);		
		if (iState == AL_PLAYING) {
			alSourceStop(m_sourceID);			
		}
	}

	if (m_pStreamingBuffer) {
		DELETE_POINTER(m_pStreamingBuffer);
	}

	alDeleteBuffers(NUMBUFFERS+1, m_aBuffers);
}

bool StreamingSound_OpenAL::play(){
	m_fFadeFactor = 1.0f;
	m_fDeltaFade = 0;
	
	return initSourceAndPlay();
}

bool StreamingSound_OpenAL::play_fadeIn(float _fadeTime) {
	m_fFadeFactor = 0;
	m_fDeltaFade = 1/_fadeTime;

	return initSourceAndPlay();
}

void StreamingSound_OpenAL::stop(){
	
	// If there is a source,... 
	if (m_sourceID != 0) {
		ALint iState;		
		alGetSourcei(m_sourceID, AL_SOURCE_STATE, &iState);		
		
		alSourceStop(m_sourceID);
		
		// Unqueue queued buffers
		int iBuffersProcessed = 0;
		alGetSourcei(m_sourceID, AL_BUFFERS_PROCESSED, &iBuffersProcessed);
	
		ALuint tempBuffer;
		while (iBuffersProcessed) {
			alSourceUnqueueBuffers(m_sourceID, 1, &tempBuffer);
			--iBuffersProcessed;
		}

		m_sourceID = 0;
	}
	m_pStreamingBuffer->close();
}

void StreamingSound_OpenAL::fadeAndStop(float fFadeTime) {
	m_fDeltaFade = -1/fFadeTime;
}

int StreamingSound_OpenAL::getState(){
	if (m_sourceID == 0) return audio::ISOUND_STOPPED;
		
		ALint	iState;		
		alGetSourcei(m_sourceID, AL_SOURCE_STATE, &iState);		
		if (iState == AL_PLAYING) {
			return audio::ISOUND_PLAYING;
		}		
		
		return audio::ISOUND_STOPPED;
}

bool StreamingSound_OpenAL::initSourceAndPlay() {
	
	stop();

	m_bBufferHasMoreSamples = true;	
		
	// Get source from the audio-engine
	
	m_sourceID = ((Audio_OpenAL*) coreGetAudio())->requestSource(this, m_iPriority);
		
	if (m_sourceID == 0) {
		coreGetLog()->WriteError("StreamingSound: Can't get source",__FILE__,__LINE__);
		return false;
	}	

	alGetError();
	ALenum error = AL_NO_ERROR;
	
	// Open the Streamingbuffer
	m_pStreamingBuffer->open();

	// Fill buffers and queue to source
	bool bHasMoreSamples;
	for (int i = 0; i < NUMBUFFERS; ++i) {
		bHasMoreSamples = m_pStreamingBuffer->fillBuffer(m_aBuffers[i]);
		if (bHasMoreSamples) {
			alSourceQueueBuffers(m_sourceID, 1, &m_aBuffers[i]);			
			error = alGetError();
			if (error != AL_NO_ERROR) {
				/// Do something
			}
		
		} else {
			m_bBufferHasMoreSamples = false;
			break;
		}
	}

	// Set volume
	float sfxVol = coreGetAudio()->getSpeechVolume();
	sfxVol *= m_fVolume;
	sfxVol *= m_fFadeFactor;
	alSourcef(m_sourceID, AL_GAIN, sfxVol);
	//alSourcef(m_sourceID, AL_GAIN, 1);
	
	alSourcePlay(m_sourceID);

	return true;
}						

void StreamingSound_OpenAL::update(const double &dt) {
	ALint	iState;		
	alGetSourcei(m_sourceID, AL_SOURCE_STATE, &iState);
	if (iState != AL_PLAYING) return; // Do updates only while playing
		
	// volume
	float sfxVol = coreGetAudio()->getSpeechVolume();
	sfxVol *= m_fVolume;		
	
	// Apply fades (In and Out)
	if (m_fDeltaFade != 0) {		
		m_fFadeFactor += m_fDeltaFade * (float)dt; 
	
		sfxVol *= m_fFadeFactor;

		// FadeOut ended
		if (m_fFadeFactor <= 0) {
			stop();
			return;
		}

		// FadeIn ended
		if (m_fFadeFactor >= 1) {
			m_fFadeFactor = 1;
			m_fDeltaFade = 0;
		}
	}
	
	if ((sfxVol >= 0) && (sfxVol <= 1)) {
		alSourcef( m_sourceID, AL_GAIN, sfxVol);
	}

	// Request the number of OpenAL Buffers that have been processed (played) on the Source
	int iBuffersProcessed = 0;
	alGetSourcei(m_sourceID, AL_BUFFERS_PROCESSED, &iBuffersProcessed);

	// For each processed buffer, remove it from the Source Queue, fill in the next chunk of audio
	// data from the StreaminBuffer and add it to the Source Queue
	while (iBuffersProcessed) {
		
		// Remove the Buffer from the Queue.  (uiBuffer contains the Buffer ID for the unqueued Buffer)
		ALuint uiBuffer = 0;
		alSourceUnqueueBuffers(m_sourceID, 1, &uiBuffer);

		// Read more audio data
		m_bBufferHasMoreSamples = m_pStreamingBuffer->fillBuffer(uiBuffer);		
		
		if (m_bBufferHasMoreSamples) {			
			// Queue buffer to source 
			alSourceQueueBuffers(m_sourceID, 1, &uiBuffer);
		}
		--iBuffersProcessed;
	}

	if (!m_bBufferHasMoreSamples) {
		m_pStreamingBuffer->close();		
	}
}



}